<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="汽车品牌" prop="brandType">
        <el-select v-model="queryParams.brandType" style="width: 192px;" placeholder="请选择品牌类型" @change="handleBrandTypeChange">
            <el-option v-for="item in brandTypeOptions" :key="item" :label="item" :value="item" ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="车型" prop="brandName">
        <el-select v-model="queryParams.brandName" style="width: 192px;" placeholder="请选择车型">
            <el-option v-for="item in brandNameOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="出厂年份" prop="yearOfManufacture">
        <el-input
          v-model="queryParams.yearOfManufacture"
          placeholder="请输入出厂年份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="行驶里程" prop="mileage">
        <el-input
          v-model="queryParams.mileage"
          placeholder="请输入行驶里程"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="燃油类型" prop="fuelType">
        <el-select v-model="queryParams.fuelType" style="width: 192px;" placeholder="请选择燃油类型" clearable>
          <el-option
            v-for="dict in used_car_fuel_type"
            :key="dict.value"
            :label="dict.value"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="变速箱类型"  prop="gearboxType">
        <el-select v-model="queryParams.gearboxType" style="width: 192px;" placeholder="请选择变速箱类型" clearable>
          <el-option
            v-for="dict in used_car_transmission_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="车身颜色" prop="color">
        <el-input
          v-model="queryParams.color"
          placeholder="请输入车身颜色"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆识别码" prop="vin">
        <el-input
          v-model="queryParams.vin"
          placeholder="请输入车辆识别码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="过户次数" prop="ownerCount">
        <el-input
          v-model="queryParams.ownerCount"
          placeholder="请输入过户次数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆状况" prop="vehicleCondition">
        <el-input
          v-model="queryParams.vehicleCondition"
          placeholder="请输入车辆状况"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入售价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker style="width: 192px;" clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上牌日期" prop="licenseDate">
        <el-date-picker style="width: 192px;" clearable
          v-model="queryParams.licenseDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择上牌日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新日期" prop="updateTime">
        <el-date-picker style="width: 192px;" clearable
          v-model="queryParams.updateTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择更新日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="排量" prop="displacement">
        <el-select v-model="queryParams.displacement" style="width: 192px;" placeholder="请选择排量" clearable>
          <el-option v-for="displacement in displacementOptions" :key="displacement" :label="displacement" :value="displacement" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="质保状态" prop="warrantyStatus">
        <el-select v-model="queryParams.warrantyStatus" style="width: 192px;" placeholder="请选择质保状态" clearable>
          <el-option v-for="warrantyStatus in warrantyOptions" :key="warrantyStatus" :label="warrantyStatus" :value="warrantyStatus" 
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['usedcar:used:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['usedcar:used:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['usedcar:used:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['usedcar:used:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="usedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车行名称" align="center" prop="nickName" />
      <el-table-column label="品牌类型" align="center" prop="brandType" />
      <el-table-column label="汽车类型" align="center" prop="brandName" />
      <el-table-column label="出厂年份" align="center" prop="yearOfManufacture" />
      <el-table-column label="行驶里程" align="center" prop="mileage" />
      <el-table-column label="排量" align="center" prop="displacement" />
      <el-table-column label="燃油类型" align="center" prop="fuelType" />
      <el-table-column label="变速箱类型" align="center" prop="gearboxType" />
      <el-table-column label="车身颜色" align="center" prop="color" />
      <el-table-column label="车辆识别码" align="center" prop="vin" />
      <el-table-column label="过户次数" align="center" prop="ownerCount" />
      <el-table-column label="车辆状况" align="center" prop="vehicleCondition" />
      <el-table-column label="质保状态" align="center" prop="warrantyStatus" />
      <el-table-column label="售价" align="center" prop="price" />
      <el-table-column label="主图路径" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="其他图片路径" align="center" prop="otherImages" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.otherImages" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上牌日期" align="center" prop="licenseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.licenseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新日期" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车辆状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['usedcar:used:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['usedcar:used:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改二手车中心对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="usedRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="品牌类型" prop="brandType">
          <el-select v-model="form.brandType" placeholder="请选择品牌类型" @change="handleBrandTypeChange">
            <el-option v-for="item in brandTypeOptions" :key="item" :label="item" :value="item" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="汽车类型" prop="brandName">
          <el-select v-model="form.brandName" placeholder="请选择车型" @change="handleBrandNameChange">
            <el-option v-for="item in brandNameOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出厂年份" prop="yearOfManufacture">
          <el-date-picker clearable
            v-model="form.yearOfManufacture"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择出厂年份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行驶里程" prop="mileage">
          <el-input v-model="form.mileage" placeholder="请输入行驶里程" />
        </el-form-item>
        <el-form-item label="排量" prop="displacement">
          <el-select v-model="form.displacement" placeholder="请选择排量" clearable>
            <el-option v-for="displacement in displacementOptions" :key="displacement" 
              :label="displacement" 
              :value="displacement" />
          </el-select>
        </el-form-item>
        <el-form-item label="燃油类型" prop="fuelType">
          <el-select v-model="form.fuelType" placeholder="请选择燃油类型">
            <el-option
              v-for="dict in used_car_fuel_type"
              :key="dict.value"
              :label="dict.value"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变速箱类型" prop="gearboxType">
          <el-select v-model="form.gearboxType" placeholder="请选择变速箱类型">
            <el-option
              v-for="dict in used_car_transmission_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车身颜色" prop="color">
          <el-input v-model="form.color" placeholder="请输入车身颜色" />
        </el-form-item>
        <el-form-item label="车辆识别码" prop="vin">
          <el-input v-model="form.vin" placeholder="请输入车辆识别码" />
        </el-form-item>
        <el-form-item label="过户次数" prop="ownerCount">
          <el-input v-model="form.ownerCount" placeholder="请输入过户次数" />
        </el-form-item>
        <el-form-item label="车辆状况" prop="vehicleCondition">
          <el-input v-model="form.vehicleCondition" placeholder="请输入车辆状况" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="新车落地价" prop="newPrice">
          <el-input v-model="form.newPrice" placeholder="请输入新车售价" />
        </el-form-item>
        <el-form-item label="主图路径" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="其他图片路径" prop="otherImages">
          <image-upload v-model="form.otherImages"/>
        </el-form-item>
        <el-form-item label="上牌日期" prop="licenseDate">
          <el-date-picker clearable
            v-model="form.licenseDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择上牌日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上牌地" prop="licenseLocation">
          <el-cascader
            v-model="form.licenseLocation"
            :options="cityOptions"
            :props="cityProps"
            placeholder="请选择上牌地"
            clearable
          />
        </el-form-item>
        <el-form-item label="车辆配置" prop="configIds">
          <el-select v-model="selectedConfigs" multiple placeholder="请选择车辆配置" style="width: 100%;">
            <el-option
              v-for="config in configOptions"
              :key="config.value"
              :label="config.label"
              :value="config.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Used">
import { listUsed, getUsed, delUsed, addUsed, updateUsed,getDisplacementList,getWarrantyList,getCityCascaderData } from "@/api/usedcar/used"
import { listTypeList,listNameList } from "@/api/usedcar/series"
import { listConfig } from "@/api/usedcar/config"

const { proxy } = getCurrentInstance()
const { used_car_fuel_type, used_car_transmission_type } = proxy.useDict('used_car_fuel_type', 'used_car_transmission_type')

const usedList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const brandTypeOptions = ref([])
const brandNameOptions = ref([])
const displacementOptions =ref([])
const warrantyOptions =ref([])
const brandNameToSeriesId = ref({})// 新增一个 ref 用于存储品牌名称和系列 ID 的映射
const configOptions = ref([]); // 存储车辆配置选项（配置ID => 配置名称）
const selectedConfigs = ref([]); // 存储选中的配置ID数组
const cityOptions = ref([]);
const cityProps = {
  value: 'value',   // 对应 CityNodeDTO 的 value
  label: 'label',   // 对应 CityNodeDTO 的 label
  children: 'children' // 对应 CityNodeDTO 的 children
};

const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    seriesId: null,
    brandType: null,
    carType: null,
    brandName: null,
    yearOfManufacture: null,
    mileage: null,
    displacement: null,
    fuelType: null,
    gearboxType: null,
    color: null,
    vin: null,
    ownerCount: null,
    vehicleCondition: null,
    warrantyStatus: null,
    price: null,
    newPrice: null,
    image: null,
    otherImages: null,
    createTime: null,
    licenseDate: null,
    updateTime: null,
    status: null,
    remark: null,
    licenseLocation: null
  },
  rules: {
    brandType: [
      { required: true, message: "品牌类型不能为空", trigger: "change" }
    ],
    brandName: [
      { required: true, message: "汽车类型不能为空", trigger: "change" }
    ],
    brandName: [
      { required: true, message: "车型不能为空", trigger: "blur" }
    ],
    yearOfManufacture: [
      { required: true, message: "出厂年份不能为空", trigger: "blur" }
    ],
    mileage: [
      { required: true, message: "行驶里程不能为空", trigger: "blur" },
      { 
        pattern: /^\d+(\.\d{1,2})?$/, // 匹配整数或最多两位小数
        message: "行驶里程需为数字（最多两位小数）", 
        trigger: "blur" 
      }
    ],
    displacement: [
      { required: true, message: "排量不能为空", trigger: "blur" }
    ],
    fuelType: [
      { required: true, message: "燃油类型不能为空", trigger: "change" }
    ],
    gearboxType: [
      { required: true, message: "变速箱类型不能为空", trigger: "change" }
    ],
    color: [
      { required: true, message: "车身颜色不能为空", trigger: "blur" }
    ],
    vin: [
      { required: true, message: "车辆识别码不能为空", trigger: "blur" }
    ],
    ownerCount: [
      { required: true, message: "过户次数不能为空", trigger: "blur" },
      { 
      pattern: /^\d+$/, // 匹配正整数（包括 0）
      message: "过户次数需为非负整数", 
      trigger: "blur" 
  }
    ],
    vehicleCondition: [
      { required: true, message: "车辆状况不能为空", trigger: "blur" }
    ],
    warrantyStatus: [
      { required: true, message: "质保状态不能为空", trigger: "change" }
    ],
    price: [
      { required: true, message: "售价不能为空", trigger: "blur" },
      { 
        pattern: /^\d+(\.\d{1,2})?$/, // 匹配整数或最多两位小数
        message: "售价需为数字（最多两位小数）", 
        trigger: "blur" 
      }
    ],
    image: [
      { required: true, message: "主图路径不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建日期不能为空", trigger: "blur" }
    ],
    licenseDate: [
      { required: true, message: "上牌日期不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新日期不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "车辆状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询二手车中心列表 */
function getList() {
  loading.value = true
  listUsed(queryParams.value).then(response => {
    usedList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    carId: null,
    seriesId: null,
    brandType: null,
    brandName: null,
    yearOfManufacture: null,
    mileage: null,
    displacement: null,
    fuelType: null,
    gearboxType: null,
    color: null,
    vin: null,
    ownerCount: null,
    vehicleCondition: null,
    warrantyStatus: null,
    price: null,
    newPrice: null,
    image: null,
    otherImages: null,
    createTime: null,
    licenseDate: null,
    licenseLocation: null,
    updateTime: null,
    status: null,
    remark: null,
    configIds: []
  }
  selectedConfigs.value = [];
  proxy.resetForm("usedRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.carId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加二手车中心"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _carId = row.carId || ids.value
  getUsed(_carId).then(response => {
    form.value = response.data
    selectedConfigs.value = form.value.configIds || [];
    open.value = true
    title.value = "修改二手车中心";
    if (form.value.brandType) {
      fetchBrandNames(form.value.brandType);
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["usedRef"].validate(valid => {
    if (valid) {
      if (form.value.licenseLocation && form.value.licenseLocation.length > 0) {
        const lastCode = form.value.licenseLocation[form.value.licenseLocation.length - 1];
        form.value.licenseLocation = findCityName(lastCode, cityOptions.value);
      } else {
        form.value.licenseLocation = '';
      }
      form.value.configIds = selectedConfigs.value;
      if (form.value.carId != null) {
        updateUsed(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addUsed(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 递归查找编码对应的城市名称
function findCityName(code, cityList) {
  for (const city of cityList) {
    if (city.value === code) {
      return city.label;
    }
    if (city.children && city.children.length > 0) {
      const result = findCityName(code, city.children);
      if (result) return result;
    }
  }
  return '';
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _carIds = row.carId || ids.value
  proxy.$modal.confirm('是否确认删除二手车中心编号为"' + _carIds + '"的数据项？').then(function() {
    return delUsed(_carIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('usedcar/used/export', {
    ...queryParams.value
  }, `used_${new Date().getTime()}.xlsx`)
}
onMounted(() => {
  fetchBrandTypes();
  fetchDisplacementList();
  fetchWarrantyList();
  fetchConfigList(); // 新增：加载车辆配置列表
  getList();
  fetchCityData();
});

const fetchCityData = async () => {
  try {
    const res = await getCityCascaderData();
    if (res.code === 200) { 
      cityOptions.value = res.data; // 直接使用 res.data 即可（已包含城市级联数据）
    } else {
      console.error('获取城市数据失败：', res.msg);
    }
  } catch (err) {
    console.error('获取城市数据异常：', err);
  }
};

function fetchBrandTypes() {
  listTypeList({}).then(res => {
    if (res.code === 200) {
      brandTypeOptions.value = res.rows;
    }
  });
}
function handleBrandTypeChange(brandType) {
  if (brandType) {
    fetchBrandNames(brandType);
    form.value.brandName = '';
  } else {
    brandNameOptions.value = [];
  }
}
function handleBrandNameChange(brandName) {
  // 根据选中的品牌名称获取对应的系列 ID
  form.value.seriesId = brandNameToSeriesId.value[brandName];
}

function fetchBrandNames(brandType) {
  listNameList(brandType).then(res => {
    if (res.code === 200) {
      // 存储品牌名称和系列 ID 的映射
      brandNameToSeriesId.value = {};
      res.rows.forEach(item => {
        brandNameToSeriesId.value[item.brandName] = item.seriesId;
      });
      brandNameOptions.value = res.rows.map(item => item.brandName);
    }
  });
}

//获取枚举
function fetchDisplacementList(){
  getDisplacementList().then(response =>{
    displacementOptions.value = response.data;
  });
}
//获取质保
function fetchWarrantyList(){
  getWarrantyList().then(response =>{
    warrantyOptions.value = response.data;
  });
}
// 加载车辆配置列表
function fetchConfigList() {
  listConfig({}).then(response => {
    if (response.code === 200) {
      configOptions.value = response.rows.map(item => ({
        value: item.configId,
        label: item.configName
      }));
    }
  });
}
getList()
</script>
<style scoped>

</style>